package com.sentrix.auto.printercenter.application;

import com.sentrix.auto.printercenter.domain.entity.PrinterEntity;
import com.sentrix.auto.printercenter.domain.entity.PrinterTaskEntity;
import com.sentrix.auto.printercenter.infrastructure.persistence.IPrinterRepository;
import com.sentrix.auto.printercenter.infrastructure.persistence.IPrinterTaskRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class PrinterTaskService {

    @Resource
    private IPrinterRepository printerRepository;
    @Resource
    private IPrinterTaskRepository taskRepository;

    public void taskSending(String agentCode, String printerName, String jobId, String taskId) {
        PrinterEntity printer = printerRepository.findByAgentCodeAndPrinterName(agentCode, printerName);
        PrinterTaskEntity task = taskRepository.getById(taskId);
        if(Objects.isNull(task)){
            return;
        }
        task.setTaskStatus(PrinterTaskEntity.TASKSTATUS.PRINTING);
        task.setGmtPrint(System.currentTimeMillis());
        taskRepository.updateById(task);
    }

    public void taskPrinting(String agentCode, String printerName, String jobId, String taskId) {
        PrinterTaskEntity task = taskRepository.getById(taskId);
        if(Objects.isNull(task)){
            return;
        }
        task.setTaskStatus(PrinterTaskEntity.TASKSTATUS.PRINTING);
        task.setGmtPrint(System.currentTimeMillis());
        taskRepository.updateById(task);
    }

    public void complete(String agentCode, String printerName, String jobId, String taskId) {
        PrinterTaskEntity task = taskRepository.getById(taskId);
        if(Objects.isNull(task)){
            return;
        }
        task.setTaskStatus(PrinterTaskEntity.TASKSTATUS.COMPLETE);
        task.setGmtPrint(System.currentTimeMillis());
        taskRepository.updateById(task);
    }

    public void failed(String agentCode, String printerName, String jobId, String taskId) {
        PrinterTaskEntity task = taskRepository.getById(taskId);
        if(Objects.isNull(task)){
            return;
        }
        task.setTaskStatus(PrinterTaskEntity.TASKSTATUS.FAILED);
        task.setGmtPrint(System.currentTimeMillis());
        taskRepository.updateById(task);
    }

}
